<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Validation\ValidationException;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     * 屏蔽指定异常写日志
     * @var array
     */
    protected $dontReport = [
        InvalidRequestException::class,
    ];

    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];


    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * @Author: hzwlxy
     * @Email: 120235331@qq.com
     * @Date: 2019/7/4 12:12
     * @Description:错误渲染，如果是ajax请求返回json,其他请求返回错误页面
     * @param \Illuminate\Http\Request $request
     * @param Exception $exception
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response|\Symfony\Component\HttpFoundation\Response
     */
    public function render($request, Exception $exception)
    {
        if ($request->expectsJson()) {
            $e = $this->prepareException($exception);
            if ($e instanceof HttpResponseException) {
                //todo...
                return $e->getResponse();
            } elseif ($e instanceof AuthenticationException) {
                return responseJsonData("没有权限");
            } elseif ($e instanceof ValidationException) {
                $err_msg = null;
                //表单验证错误
                foreach ($exception->errors() as $err) {
                    $err_msg = $err[0];
                    break;
                }
                return responseJsonData($err_msg);
            }
            return responseJsonData($e->getMessage());
        } else {
            return parent::render($request, $exception);
        }

    }
}
